package com.java.sample.mac;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

public class MacAddressFetcher {

    public static void main(String[] args) {
        try {
            System.out.println("本地MAC地址: " + getLocalMacAddress().stream().collect(Collectors.joining(",")));
        } catch (SocketException e) {
            System.err.println("获取MAC地址失败: " + e.getMessage());
        }
    }

    public static List<String> getLocalMacAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        List<String> list = new ArrayList<>();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();

            // 跳过回环接口和虚拟接口
            if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                continue;
            }

            byte[] mac = networkInterface.getHardwareAddress();

            if (mac != null && mac.length > 0) {
                list.add(formatMacAddress(mac));
            }
        }
        if(list.isEmpty()){
            throw new SocketException("未找到有效的MAC地址");
        }
        return list;
    }

    private static String formatMacAddress(byte[] mac) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
        }
        return sb.toString();
    }
}
